import json
import threading

from model.db.name_mapping import refresh_name_cache
from utils.utils import redis_client, REDIS_PUB_SUB_CHANNEL


def publish_refresh_event(name_type):
    '''
    往通道中发送消息
    '''
    msg = json.dumps({'action': 'refresh', 'name_type': name_type})
    redis_client.publish(REDIS_PUB_SUB_CHANNEL, msg)
    print(f"[REDIS PUBLISH] {msg}")


def start_subscriber(app):
    '''
    订阅通道 并做业务逻辑的处理
    '''

    def _sub_watcher():
        pubsub = redis_client.pubsub()
        pubsub.subscribe(REDIS_PUB_SUB_CHANNEL)

        print(f"[SUBSCRIBER] Subscribed to Redis channel: {REDIS_PUB_SUB_CHANNEL}")

        # Notice 阻塞操作
        for message in pubsub.listen():
            print('message:>>> ', message)
            if message['type'] == 'message':
                handle_message(app, message)

    # 启动 Redis 订阅线程
    thread = threading.Thread(target=_sub_watcher)
    # Notice 设置为守护线程 跟随flask项目主线程共同停止
    thread.daemon = True
    thread.start()


def handle_message(app, msg):
    try:
        data = json.loads(msg['data'])
        if data.get('action') == 'refresh':
            print(f"[REDIS SUBSCRIBE] Received refresh signal for name_type={data['name_type']}")
            with app.app_context():
                refresh_name_cache()
    except Exception as e:
        print("[ERROR] Failed to process message:", e)
